﻿using DL.Tools;
using UnityEngine;

namespace DL
{
    public class VFXEmitter : MonoBehaviour
    {
        //粒子系统
        private ParticleSystem[] m_PS;
        public float playTime; //播放时间
        public float playSpeed; //播放速度
        public VFXConfig Config;
        public string m_Owner;

        private bool m_IsReCycle;
        public void Awake()
        {
            m_PS = GetComponentsInChildren<ParticleSystem>();
            foreach (var ps in m_PS)
            {
                VFXManager.Inst.AddParticleSystem(ps);
            }
        }

        public void Init(string owner,VFXConfig config)
        {
            m_Owner = owner;
            Config = config;
        }

        public VFXEmitter WithPlayTime(float playTime)
        {
            this.playTime = playTime;
            return this;
        }
        
        public VFXEmitter WithplaySpeed(float playSpeed)
        {
            this.playSpeed = playSpeed;
            return this;
        }

        //启用
        public void Play()
        {
            foreach (var ps in m_PS)
            {
                var main = ps.main;
                main.simulationSpeed = playSpeed;
                ps.Play();
            }
            Debugger.EO_Log("播发特效："+ Config.name);
            m_IsReCycle = false;
            NewTimerManager.Inst.GetTimer(playTime, ReCycle);
        }

        //关闭
        public void ReCycle()
        {
            foreach (var ps in m_PS)
            {
                ps.Stop();
            }
            
            //为了避免被多次回收
            if(m_IsReCycle) return;

            ResetConfig();
            
            m_IsReCycle = true;
            VFXPoolManager.Inst.ReleaseVFX(this);
        }

        private void ResetConfig()
        {
            playSpeed = 1;
            playTime = 1;
        }
    }
}